<template>
  <!-- 外卖订单 -->
  <div class="takeout-order">
    <Return />
    <div class="takeout-order-header" :style="{ height: headerHeight + 'px' }">
      <div class="takeout-order-header-bottom">
        <template v-for="(item, index) in takeoutOrderList" :key="item.title">
          <div class="takeout-order-header-bottom-item">
            <div class="item-box" :class="{ 'item-box-active': index === activeIndex }" @click="handleTabChange(index)">
              <div>{{ item.title }}</div>
            </div>
          </div>
        </template>
      </div>
    </div>
    <scroll-view class="takeout-order-content" scroll-y="true" :style="{ height: contentHeight + 'px' }"
      @scrolltolower="loadMore" @refresherrefresh="onRefresh" :refresher-enabled="true"
      :refresher-triggered="refreshing">
      <div v-if="loading && orderList.length === 0" class="loading-container">
        <div class="loading">加载中...</div>
      </div>

      <div v-else-if="orderList.length === 0" class="empty-container">
        <div class="empty-text">暂无订单</div>
      </div>

      <template v-else>
        <div v-for="(order, orderIndex) in orderList" :key="order.id" class="takeout-order-content-item"
          @click="viewOrderDetail(order)">
          <div class="takeout-order-content-item-header">
            <img :src="order.storeAvatar || '../static/imgs/banner.png'" alt="">
            <div class="takeout-order-content-item-header-title">
              <div class="takeout-order-content-item-header-title-top">
                <span class="store-name">{{ order.shopName }}</span>
                <span class="store-name-tag" :class="getStatusClass(order.status)">
                  {{ getStatusText(order.status) }}
                </span>
              </div>
              <div class="takeout-order-content-item-header-title-button">
                <span>订单号：{{ order.orderNo }}</span>
              </div>
            </div>
          </div>
          <div class="page-line"> </div>
          <div class="item-center">
            <template v-for="(item, index) in order.items" :key="index">
              <div class="info">
                <img :src="item.image || '../static/imgs/banner.png'" alt="">
                <div class="info-content">
                  <div class="info-content-top">
                    <span class="store-name">{{ item.name }}</span>
                    <span class="store-name-tag">
                      <i>实付</i> <i>¥</i> <i>{{ item.priceStr }}</i>
                    </span>
                  </div>
                  <div class="info-content-button" v-if="item.remark">
                    <div class="info-content-button-item-remark">
                      <div>{{ item.remark }}</div>
                    </div>
                  </div>
                  <div class="info-content-button">
                    <div class="info-content-button-item">
                      <div>x</div>
                      <div>{{ item.quantity }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </div>
          <div class="total-priceStr">
            <div>共计</div>
            <div>¥</div>
            <div>{{ order.totalAmountStr }}</div>
          </div>
          <div class="page-line"> </div>
          <div class="takeout-order-content-item-footer">
            <div class="footer-item" v-if="order.remark">
              <div class="footer-item-left">备注</div>
              <div class="footer-item-right">{{ order.remark }}</div>
            </div>
            <div class="footer-item">
              <div class="footer-item-left">创建时间</div>
              <div class="footer-item-right">{{ formatCreateTime(order.createTime) }}</div>
            </div>
            <div class="footer-item">
              <div class="footer-item-left">收货地址</div>
              <div class="footer-item-right">{{ order.deliveryAddress }}</div>
            </div>
            <div class="footer-item" v-if="order.distributionName">
              <div class="footer-item-left">骑手</div>
              <div class="footer-item-right">{{ order.distributionName }}</div>
            </div>
          </div>

          <!-- 订单操作按钮 -->
          <div class="order-actions" v-if="order.status !== 'completed' && order.status !== 'refunded'">
            <div class="action-buttons">
              <!-- 状态为4时显示确认收货 -->
              <!-- <div v-if="order.status === '4'" class="action-btn primary" @click.stop="confirmReceive(order)">
                确认收货
              </div> -->
              <!-- 状态为4时显示申请退款 -->
              <!-- <div v-if="order.status === '4'" class="action-btn"
                :class="order.refundRequestList.length > 0 ? 'refund-pending' : 'apply-refund'"
                @click.stop="applyRefund(order)">
                {{ order.refundRequestList.length > 0 ? '退款审核中' : '申请退款' }}
              </div> -->
              <!-- 其他状态的按钮保持不变 -->
              <div v-if="order.status === 'preparing' || order.status === 'delivering'" class="action-btn secondary"
                @click.stop="cancelOrder(order)">
                取消订单
              </div>
            </div>
          </div>
        </div>
      </template>

      <div v-if="loadingMore" class="loading-more">
        <div class="loading-text">加载更多...</div>
      </div>
    </scroll-view>
  </div>

  <!-- 添加退款弹窗 -->
  <wd-popup v-model="showRefundDialog" position="center">
    <view class="refund-dialog">
      <view class="refund-dialog-header">
        <text class="title">申请退款</text>
        <text class="close" @click="showRefundDialog = false">×</text>
      </view>
      <view class="refund-dialog-content">
        <view class="input-group">
          <text class="label">退款原因</text>
          <textarea v-model="refundCause" placeholder="请输入退款原因" class="textarea" />
        </view>
        <view class="input-group">
          <text class="label">上传凭证（最多3张）</text>
          <view class="image-upload">
            <view v-for="(img, index) in refundImg" :key="index" class="image-item">
              <image :src="img" mode="aspectFill" />
              <text class="delete-btn" @click="deleteImage(index)">×</text>
            </view>
            <view v-if="refundImg.length < 3" class="upload-btn" @click="uploadImage">
              <text class="plus">+</text>
            </view>
          </view>
        </view>
      </view>
      <view class="refund-dialog-footer">
        <button class="cancel-btn" @click="showRefundDialog = false">取消</button>
        <button class="submit-btn" @click="handleRefundSubmit">确认</button>
      </view>
    </view>
  </wd-popup>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { Fetch } from '@/composables/useFetch'
import Return from '@/components/Return.vue'
import { baseUrl } from '@/utils/config'
// 获取用户数据
import { useLoginStore } from '@/stores/login'
const loginStore = useLoginStore()
const headerHeight = ref(0)
const contentHeight = ref(0)
const activeIndex = ref(0)
const orderList = ref([])
const loading = ref(false)
const loadingMore = ref(false)
const refreshing = ref(false)
const page = ref(1)
const hasMore = ref(true)

// 添加退款相关的响应式变量
const showRefundDialog = ref(false)
const refundCause = ref('')
const refundImg = ref([])
const currentRefundOrder = ref(null)

// 修改标签页配置
const takeoutOrderList = ref([
  { title: '全部订单', status: 'all' },
  { title: '进行中', status: 'inProgress' }, // 修改为数组，包含所有进行中状态
  { title: '已完成', status: 'finish' },
])

// 计算当前状态
const currentStatus = computed(() => {
  return takeoutOrderList.value[activeIndex.value]?.status || 'all'
})

// 状态文本映射
const statusTextMap = {
  '0': '待接单',
  '1': '已接单',
  '2': '待配送',
  '3': '配送中',
  '4': '骑手配送完成-已完成',
  '5': '已完成',
  '6': '已取消',
  '7': '退款中',
  '8': '退款完成',
  '9': '订单已取消',
}

// 获取状态文本
const getStatusText = (status) => {
  return statusTextMap[status] || '订单未支付'
}

// 获取状态对应的样式类
const getStatusClass = (status) => {
  const statusMap = {
    '1': 'status-1',      // 待接单
    '2': 'status-2',      // 待配送
    '3': 'status-3',      // 配送中
    '4': 'status-4',      // 骑手配送完成-已完成
    '5': 'status-5',      // 已完成
    '6': 'status-6',      // 已取消
    '7': 'status-7',      // 状态7
    '8': 'status-8',      // 状态8
    '9': 'status-9'       // 状态9
  }
  return statusMap[status] || 'status-default'
}

// 计算内容区高度
function calcContentHeight() {
  const systemInfo = uni.getSystemInfoSync()
  // #ifdef MP-WEIXIN
  const menuButtonInfo = wx.getMenuButtonBoundingClientRect()
  headerHeight.value = menuButtonInfo.bottom + 54
  // #endif
  contentHeight.value = systemInfo.windowHeight - headerHeight.value - (systemInfo.safeAreaInsets?.bottom || 0)
}

// 获取订单列表
const fetchOrderList = async (isRefresh = false) => {
  if (loading.value || loadingMore.value) return

  if (isRefresh) {
    page.value = 1
    hasMore.value = true
    loading.value = true
  } else {
    loadingMore.value = true
  }

  try {
    const params = {
      pageNum: page.value,
      pageSize: 10,
    };

    // 如果不是"全部"，则添加状态筛选
    if (currentStatus.value !== 'all') {
      // 如果是数组（进行中状态），使用数组
      if (currentStatus.value == 8) {

        params.status = currentStatus.value; // 后端需要支持数组查询
      } else {
        params.searchValue = currentStatus.value;
      }
    }

    const { data } = await Fetch('shopping/order/findOrderList', {
      method: 'GET',
      data: params
    })
    console.log(data, 'data!!!');

    if (data.code === 200) {
      const newOrders = data.rows || []

      if (isRefresh) {
        orderList.value = newOrders
      } else {
        orderList.value = [...orderList.value, ...newOrders]
      }

      hasMore.value = newOrders.length === 10
      if (hasMore.value) {
        page.value++
      }
    } else {
      if (data.code === 403) {
        uni.showModal({
          title: '提示',
          content: '请先登录',
          success: (res) => {
            if (res.confirm) {
              uni.reLaunch({
                url: '/pages/login'
              });
            }
          }
        })
        return
      }
      uni.showToast({
        title: typeof data?.msg === 'string' && data.msg ? data.msg : '获取订单失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  } finally {
    loading.value = false
    loadingMore.value = false
    refreshing.value = false
  }
}

// 切换标签
const handleTabChange = (index) => {
  if (activeIndex.value === index) return
  activeIndex.value = index
  orderList.value = []
  page.value = 1
  hasMore.value = true
  fetchOrderList(true)
}

// 加载更多
const loadMore = () => {
  if (hasMore.value && !loadingMore.value) {
    fetchOrderList()
  }
}

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true
  fetchOrderList(true)
}

// 查看订单详情
const viewOrderDetail = (order) => {
  uni.navigateTo({
    url: `/pages/OrderDetails?id=${order.orderId}`
  })
}

// 确认收货
const confirmReceive = async (order) => {
  uni.showModal({
    title: '确认收货',
    content: '确认已收到商品吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const { data } = await Fetch(`takeout/orders/${order.id}/confirm`, {
            method: 'POST'
          })

          if (data.code === 0) {
            uni.showToast({
              title: '确认收货成功',
              icon: 'success'
            })
            // 刷新订单列表
            fetchOrderList(true)
          } else {
            uni.showToast({
              title: typeof data?.msg === 'string' && data.msg ? data.msg : '操作失败',
              icon: 'none'
            })
          }
        } catch (error) {
          uni.showToast({
            title: '网络错误',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 取消订单
const cancelOrder = async (order) => {
  uni.showModal({
    title: '取消订单',
    content: '确认取消该订单吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const { data } = await Fetch(`takeout/orders/${order.id}/cancel`, {
            method: 'POST'
          })

          if (data.code === 0) {
            uni.showToast({
              title: '取消订单成功',
              icon: 'success'
            })
            fetchOrderList(true)
          } else {
            uni.showToast({
              title: typeof data?.msg === 'string' && data.msg ? data.msg : '操作失败',
              icon: 'none'
            })
          }
        } catch (error) {
          uni.showToast({
            title: '网络错误',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 修改申请退款函数
const applyRefund = (order) => {
  currentRefundOrder.value = order
  showRefundDialog.value = true
}

// 添加处理退款提交的函数
const handleRefundSubmit = async () => {
  if (!refundCause.value) {
    uni.showToast({
      title: '请输入退款原因',
      icon: 'none'
    })
    return
  }

  try {
    const params = {
      orderId: currentRefundOrder.value.orderId,
      refundCause: refundCause.value,
      refundImg: refundImg.value.join(','), // 将图片数组转换为逗号分隔的字符串
    }

    const { data } = await Fetch('shopping/refundRequest/add', {
      method: 'POST',
      data: params
    })

    if (data.code === 200) {
      uni.showToast({
        title: '申请退款成功',
        icon: 'success'
      })
      showRefundDialog.value = false
      refundCause.value = ''
      refundImg.value = []
      fetchOrderList(true)
    } else {
      uni.showToast({
        title: data.msg || '申请退款失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('申请退款失败:', error)
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  }
}

// 添加上传图片的函数
const uploadImage = () => {
  uni.chooseImage({
    count: 3 - refundImg.value.length, // 最多上传3张图片
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: async (res) => {
      const tempFilePaths = res.tempFilePaths
      for (let path of tempFilePaths) {
        try {
          // 这里需要替换成你的图片上传接口
          const uploadRes = await uni.uploadFile({
            url: `${baseUrl}shopping/sysFile/upload`,
            filePath: path,
            name: 'file',
            header: {
              'accesstoken': loginStore.token || ''
            },
          })
          const result = JSON.parse(uploadRes.data)
          if (result.code === 200) {
            refundImg.value.push(result.data.fileUrl)
          }
        } catch (error) {
          console.error('上传图片失败:', error)
        }
      }
    }
  })
}

// 删除已上传的图片
const deleteImage = (index) => {
  refundImg.value.splice(index, 1)
}

// 添加格式化创建时间的方法
const formatCreateTime = (createTime) => {
  if (!createTime) return '暂无'

  try {
    const date = new Date(createTime)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')

    return `${year}-${month}-${day} ${hours}:${minutes}`
  } catch (error) {
    console.error('时间格式化失败:', error)
    return '时间格式错误'
  }
}

// 监听状态变化
watch(currentStatus, () => {
  if (orderList.value.length > 0) {
    fetchOrderList(true)
  }
})

onMounted(() => {
  calcContentHeight()
  uni.onWindowResize && uni.onWindowResize(calcContentHeight)


})
onShow(() => {
  // 初始加载数据
  fetchOrderList(true)
})
</script>

<style lang="scss" scoped>
.takeout-order {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;

  .takeout-order-header {
    background: #FFFFFF;
    position: relative;
    margin-bottom: 20rpx;
    z-index: 2;

    .takeout-order-header-bottom {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 96rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .takeout-order-header-bottom-item {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;

        .item-box {
          font-weight: bold;
          font-size: 28rpx;
          color: #191919;
          line-height: 40rpx;
          text-align: center;
          font-style: normal;
          text-transform: none;
          cursor: pointer;
        }

        .item-box-active {
          position: relative;

          &::after {
            content: '';
            display: block;
            width: 40rpx;
            height: 8rpx;
            background: #F9DC40;
            border-radius: 4rpx 4rpx 4rpx 4rpx;
            position: absolute;
            bottom: -10rpx;
            left: 50%;
            transform: translateX(-50%);
          }
        }
      }
    }
  }

  .takeout-order-content {
    overflow: auto;
    background: #F5F5F5;
    padding: 0 20rpx;
    box-sizing: border-box;

    .loading-container,
    .empty-container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 200rpx;
      background: #F5F5F5;
      border-radius: 20rpx;
      margin-top: 20rpx;
    }

    .loading {
      font-size: 28rpx;
      color: #999999;
    }

    .empty-text {
      font-size: 28rpx;
      color: #999999;
    }

    .takeout-order-content-item {
      width: 710rpx;
      background: #FFFFFF;
      border-radius: 20rpx 20rpx 20rpx 20rpx;
      padding: 24rpx;
      box-sizing: border-box;
      margin-bottom: 20rpx;

      .takeout-order-content-item-header {
        display: flex;
        align-items: center;
        margin-bottom: 32rpx;

        image {
          width: 76rpx;
          height: 76rpx;
          border-radius: 16rpx 16rpx 16rpx 16rpx;
          margin-right: 16rpx;
        }

        .takeout-order-content-item-header-title {
          flex: 1;

          .takeout-order-content-item-header-title-top {
            display: flex;
            align-items: center;

            .store-name {
              font-size: 30rpx;
              color: #000000;
              font-weight: bold;
            }

            .store-name-tag {
              font-weight: 400;
              font-size: 26rpx;
              color: #666666;
              line-height: 36rpx;
              text-align: center;
              font-style: normal;
              text-transform: none;
              margin-left: auto;
            }
          }

          .takeout-order-content-item-header-title-button {
            display: flex;
            color: #A0A0A0;
            font-size: 22rpx;
            margin-top: 10rpx;

            label {
              display: block;
              font-size: 24rpx;
              color: #9B9B9B;
              font-weight: normal;
              margin-right: 24rpx;
            }
          }
        }

      }

      .item-center {
        margin-top: 32rpx;
      }

      .total-priceStr {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        margin-top: 18rpx;
        margin-bottom: 30rpx;

        view {
          font-size: 22rpx;

          &:nth-child(1) {
            font-size: 30rpx;
          }

          &:nth-child(2) {
            font-size: 30rpx;
            margin: 0 5rpx;
          }

          &:nth-child(3) {
            font-size: 36rpx;
            font-weight: bold;
          }
        }
      }

      .takeout-order-content-item-footer {
        margin-top: 30rpx;

        .footer-item {
          display: flex;
          font-size: 26rpx;
          color: #191919;
          margin-bottom: 20rpx;

          .footer-item-left {
            flex: 1;
          }

          .footer-item-right {
            width: 300rpx;
            text-align: right;
          }
        }
      }

      .order-actions {
        margin-top: 30rpx;

        .action-buttons {
          display: flex;
          justify-content: flex-end;
          gap: 20rpx;

          .action-btn {
            padding: 10rpx 20rpx;
            border-radius: 8rpx;
            font-size: 28rpx;
            font-weight: bold;
            text-align: center;

            &.primary {
              background-color: #F9DC40;
              color: #191919;
            }

            &.secondary {
              background-color: #E0E0E0;
              color: #191919;
            }

            &.refund-pending {
              background-color: #FFC107;
              /* 退款审核中样式 */
              color: #191919;
            }

            &.apply-refund {
              background-color: #4CAF50;
              /* 申请退款样式 */
              color: #FFFFFF;
            }
          }
        }
      }
    }
  }
}

.info {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;

  image {
    width: 98rpx;
    height: 98rpx;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
  }

  .info-content {
    flex: 1;
    margin-left: 20rpx;

    .info-content-top {
      display: flex;

      .store-name {
        font-size: 26rpx;
        color: #191919;
        line-height: 36rpx;
        text-align: center;
        font-style: normal;
        text-transform: none;
      }

      .store-name-tag {
        display: flex;
        align-items: center;
        color: #191919;
        margin-left: auto;

        view {
          font-size: 22rpx;

          &:nth-child(1) {
            font-size: 26rpx;
          }

          &:nth-child(2) {
            font-size: 22rpx;
            margin: 0 5rpx;
          }

          &:nth-child(3) {
            font-size: 32rpx;
            font-weight: bold;
          }
        }
      }

    }

    .info-content-button-item-remark {
      font-size: 22rpx;
      color: #999999;
    }

    .info-content-button-item {
      display: flex;
      align-items: center;
      color: #999999;
      font-size: 22rpx;
    }
  }
}

.page-line {
  width: 662rpx;
  height: 1rpx;
  background: #F5F5F5;
}

.refund-dialog {
  width: 650rpx;
  background: #FFFFFF;
  border-radius: 20rpx;
  overflow: hidden;

  .refund-dialog-header {
    padding: 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1rpx solid #F5F5F5;

    .title {
      font-size: 32rpx;
      font-weight: bold;
      color: #191919;
    }

    .close {
      font-size: 40rpx;
      color: #999999;
      padding: 0 20rpx;
    }
  }

  .refund-dialog-content {
    padding: 30rpx;

    .input-group {
      margin-bottom: 30rpx;

      .label {
        display: block;
        font-size: 28rpx;
        color: #191919;
        margin-bottom: 20rpx;
      }

      .textarea {
        width: 100%;
        height: 200rpx;
        background: #F5F5F5;
        border-radius: 10rpx;
        padding: 20rpx;
        font-size: 28rpx;
      }

      .image-upload {
        display: flex;
        flex-wrap: wrap;
        gap: 20rpx;

        .image-item {
          position: relative;
          width: 160rpx;
          height: 160rpx;

          image {
            width: 100%;
            height: 100%;
            border-radius: 10rpx;
          }

          .delete-btn {
            position: absolute;
            top: -20rpx;
            right: -20rpx;
            width: 40rpx;
            height: 40rpx;
            background: rgba(0, 0, 0, 0.5);
            border-radius: 50%;
            color: #FFFFFF;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24rpx;
          }
        }

        .upload-btn {
          width: 160rpx;
          height: 160rpx;
          background: #F5F5F5;
          border-radius: 10rpx;
          display: flex;
          align-items: center;
          justify-content: center;

          .plus {
            font-size: 60rpx;
            color: #999999;
          }
        }
      }
    }
  }

  .refund-dialog-footer {
    padding: 30rpx;
    display: flex;
    justify-content: flex-end;
    gap: 20rpx;
    border-top: 1rpx solid #F5F5F5;

    button {
      width: 180rpx;
      height: 80rpx;
      border-radius: 40rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .cancel-btn {
      background: #F5F5F5;
      color: #191919;
    }

    .submit-btn {
      background: #F9DC40;
      color: #191919;
    }
  }
}

.store-name-tag {
  // 基础样式
  padding: 8rpx 16rpx;
  border-radius: 16rpx;
  font-size: 22rpx;
  font-weight: 500;

  // 不同状态的颜色
  &.status-1 {
    background-color: #e3f2fd;
    color: #1976d2;
  }

  &.status-2 {
    background-color: #fff3e0;
    color: #f57c00;
  }

  &.status-3 {
    background-color: #e8f5e8;
    color: #388e3c;
  }

  &.status-4 {
    background-color: #f3e5f5;
    color: #7b1fa2;
  }

  &.status-5 {
    background-color: #e8f5e8;
    color: #388e3c;
  }

  &.status-6 {
    background-color: #ffebee;
    color: #d32f2f;
  }

  &.status-7 {
    background-color: #fce4ec;
    color: #c2185b;
  }

  &.status-8 {
    background-color: #e0f2f1;
    color: #00695c;
  }

  &.status-9 {
    background-color: #fff8e1;
    color: #f57f17;
  }
}
</style>
